<template>
  <div />
</template>
<script>
import $ from 'jquery';
import JyMagnifier from './canvas.magnifier';

export default {
  props: {
    // 功能组件 放大镜/聚光灯
    tools: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      // 聚光灯功能不需要放大
      ratio: this.tools === 'magnifyingGlass' ? 2 : 1,
      magnifier: null,
      canvas: null,
      isblack: false,
      width: 380,
      height: 300,
    };
  },
  watch: {
    tools: {
      handler(v) {
        // tools变化,镜框消失,这里的场景是打开放大镜,没关闭,又打开聚光灯,会走这里
        this.magnifier && this.magnifier.show(false);
        this.ratio = v === 'magnifyingGlass' ? 2 : 1;
        this.width = 380;
        this.height = 300;
        this.init();
      },
      deep: true,
    },
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    // 关闭放大镜 关闭当前授课时的关闭
    closeMagnifyingGlass() {
      this.magnifier && this.magnifier.show(false);
      this.blackDiv ? (this.blackDiv.style.display = 'none') : '';
      this.banblackDiv ? (this.banblackDiv.style.display = 'none') : '';
    },
    async init() {
      const { capturePage } = window.electronAPI;

      if (!capturePage) {
        this.$message({
          showClose: true,
          message: '请在客户端操作',
          type: 'warning',
          duration: 5000,
        });
        return;
      }

      try {
        // 获取客户端截图 base64 数据
        const obj = await capturePage(/* 可选的截图参数 */);
        const { img = '', size: { width = '', height = '' } = {} } = obj || {};
        // console.log('width ===> ', width, height);
        // console.log('obj =============> ', obj);
        // 创建 canvas 元素
        const canvasT = document.createElement('canvas');
        // 存储canvas 便于关闭移除
        this.canvasT = canvasT;
        // canvas的宽高就是图片的宽高
        canvasT.width = width;
        canvasT.height = height;
        canvasT.style.width = `${width}px`;
        canvasT.style.height = `${height}px`;
        canvasT.style.display = 'none'; // 最初先隐藏，避免影响布局
        canvasT.id = 'pdf-canvas-id';
        const canvasTcontext = canvasT.getContext('2d');

        // 创建图片对象并加载图片数据
        const imgObj = new Image();
        imgObj.src = img;
        imgObj.onload = () => {
          // console.log('图片加载完成');
          // 绘制图片到 canvas
          canvasTcontext.drawImage(imgObj, 0, 0);
          // 将 canvas 添加到页面中
          $('body').append(canvasT);
          // 显示 canvas
          canvasT.style.display = 'block';

          // 执行其他初始化操作
          this.initDo();
        };
      } catch (error) {
        console.error('截图失败:', error);
      }
    },

    initDo() {
      // 隐藏不必要的 DOM 元素
      document.getElementById('ment-container').style.display = 'none';
      document.getElementById('ment-left-container').style.display = 'none';

      if (this.blackDiv) this.blackDiv.style.display = 'none';
      if (this.banblackDiv) this.banblackDiv.style.display = 'none';
      this.isblack = false;
      const canvasId = 'pdf-canvas-id';
      const canvas = document.querySelector('canvas');
      this.canvas = canvas;
      // 展示框（放大镜和聚光灯的框）
      const magnifier = JyMagnifier({
        targetCanvasId: canvasId,
        width: this.width,
        height: this.height,
        radius: 0,
        ratio: this.ratio,
        sightType: 'rect',
        sightSize: 0,
        sightColor: 'black',
        magnifierDivStyle: 'border:2px solid #FC8B09;',
      });
      this.magnifier = magnifier;
      this.magnifier.show(true);
      // 镜框移动监听
      const drag = this.magnifier.magnifierObject();
      drag.addEventListener('mousedown', this.tuozhuai);
      drag.addEventListener('touchstart', this.tuozhuai);
      // 镜框拉伸监听(四个角)
      const coor = this.magnifier.coorObject();
      const coorzx = this.magnifier.coorzxObject();
      const coorzs = this.magnifier.coorzsObject();
      const coorys = this.magnifier.coorysObject();
      coor.addEventListener('mousedown', this.tuozhuaiCoor);
      coorzx.addEventListener('mousedown', this.tuozhuaiCoor);
      coorzs.addEventListener('mousedown', this.tuozhuaiCoor);
      coorys.addEventListener('mousedown', this.tuozhuaiCoor);
      // 触摸处理: touchstart,touchmove,touchend
      coor.addEventListener('touchstart', this.tuozhuaiCoor);
      coorzx.addEventListener('touchstart', this.tuozhuaiCoor);
      coorzs.addEventListener('touchstart', this.tuozhuaiCoor);
      coorys.addEventListener('touchstart', this.tuozhuaiCoor);
      if (this.tools === 'magnifyingGlass') drag.addEventListener('mousewheel', this.doMousewheel, false);

      // 关闭/关灯按钮
      const menu = this.magnifier.menuObject();
      const blackDiv = document.createElement('div');
      this.blackDiv = blackDiv;
      const banblackDiv = document.createElement('div');
      this.banblackDiv = banblackDiv;
      // 聚光灯,需要除了镜框以外部分半透明;放大镜这里给一个透明的遮罩层(解决tuozhuaiCoor放大缩小move事件不生效问题;还解决点击镜框之外区域触发上一下下一页问题)
      if (this.tools === 'spotlight') {
        this.spotlight('spotlight');
      } else if (this.tools === 'magnifyingGlass') {
        this.spotlight('magnifyingGlass');
      }
      menu.addEventListener(
        'click',
        (event) => {
          if (event.offsetX > 34) {
            // 关闭(关灯效果关闭,放大镜关闭,tools置空,解除监听)
            blackDiv.style.display = 'none';
            banblackDiv.style.display = 'none';
            this.magnifier.show(false);
            this.$emit('clearTools');
            document.removeEventListener('mousedown', this.tuozhuai);
            document.removeEventListener('touchstart', this.tuozhuai);
            // 关闭放大镜，聚光灯 移除 id=pdf-canvas-id 的元素
            // 删除框下面的操作按钮
            $('#menuId').remove();
            // 移除canvas
            this.canvasT.remove();
            // 移除关灯效果
            blackDiv.remove();
            banblackDiv.remove();
            $('.magnifyingGlassAndSpotlight').remove();

            document.getElementById('ment-container').style.display = 'flex';
            document.getElementById('ment-left-container').style.display = 'flex';
          } else if (!this.isblack) {
            this.isblack = true;
            // 关灯(创建一个黑div)
            blackDiv.setAttribute(
              'style',
              'z-index:0;position:absolute;display:block;width:100%;height:-webkit-fill-available;background-color:#000;',
            );
            blackDiv.style.top = '0px';
            blackDiv.style.left = '0px';
            document.body.appendChild(blackDiv);
          } else if (this.isblack) {
            // 开灯
            this.isblack = false;
            blackDiv.style.display = 'none';
          }
        },
        false,
      );
    },
    spotlight(type) {
      if (type === 'magnifyingGlass') {
        this.banblackDiv.setAttribute(
          'style',
          'z-index:0;position:absolute;display:block;width:100%;height:-webkit-fill-available;background-color:rgb(0,0,0,0.0);',
        );
      } else if (type === 'spotlight') {
        this.banblackDiv.setAttribute(
          'style',
          'z-index:0;position:absolute;display:block;width:100%;height:-webkit-fill-available;background-color:rgb(0,0,0,0.5);',
        );
      }
      this.banblackDiv.style.top = '0px';
      this.banblackDiv.style.left = '0px';
      document.body.appendChild(this.banblackDiv);
    },
    tuozhuaiCoor(e) {
      // 阻止冒泡
      e.cancelBubble = true;
      // 父div
      const box = document.getElementById('magnifierId');
      const w = box.offsetWidth;
      const h = box.offsetHeight;
      const onMove = (event) => {
        let width;
        let height;
        const dpageX = e.pageX || e.targetTouches[0].pageX;
        const dpageY = e.pageY || e.targetTouches[0].pageY;
        const mpageX = event.pageX || event.targetTouches[0].pageX;
        const mpageY = event.pageY || event.targetTouches[0].pageY;
        // 镜框div相对浏览器位置
        const magnifierleft = box.offsetLeft;
        const magnifiertop = box.offsetTop;
        if (e.target.id === 'coorId') {
          // 计算拉伸时镜框的宽高,右下角拉伸-移动偏移量减去点击时鼠标的坐标+原来的宽高
          width = Math.max(60, mpageX - dpageX + w);
          height = Math.max(30, mpageY - dpageY + h);
        } else if (e.target.id === 'coorzxId') {
          // 计算拉伸时镜框的宽高,左下角拉伸
          width = Math.max(60, dpageX - mpageX + w);
          height = Math.max(30, mpageY - dpageY + h);
          if (width > 60 && height > 30) {
            box.style.left = `${mpageX}px`;
          }
        } else if (e.target.id === 'coorzsId') {
          // 计算拉伸时镜框的宽高,左上角拉伸
          width = Math.max(60, dpageX - mpageX + w);
          height = Math.max(30, dpageY - mpageY + h);
          if (width > 60 && height > 30) {
            box.style.left = `${mpageX}px`;
            box.style.top = `${mpageY}px`;
          }
        } else if (e.target.id === 'coorysId') {
          // 计算拉伸时镜框的宽高,右上角拉伸
          width = Math.max(60, mpageX - dpageX + w);
          height = Math.max(30, dpageY - mpageY + h);
          if (width > 60 && height > 30) {
            box.style.top = `${mpageY}px`;
          }
        }
        // 调用放大镜里的setWH,拉伸镜框效果;w,h为了计算镜框内容开始的offset
        this.magnifier.setWH(width, height, magnifierleft, magnifiertop, w, h);
      };
      const onUp = () => {
        const box = document.getElementById('magnifierId');
        const w = box.offsetWidth;
        const h = box.offsetHeight;
        document.removeEventListener('mousemove', onMove);
        document.removeEventListener('mouseup', onUp);
        document.removeEventListener('touchmove', onMove);
        document.removeEventListener('touchend', onUp);
        // 拉伸事件结束时,重置复制内容canvas的宽高,否则镜框太宽/高时会出现放大不全的情况
        this.magnifier.resethackCanvas(w, h);
        // 重置镜框宽高,保证拖动镜框时显示正常,-4是因为边框的宽高,否则右下角按钮定位有出入
        this.width = box.offsetWidth - 4;
        this.height = box.offsetHeight - 4;
      };
      document.addEventListener('mousemove', onMove);
      document.addEventListener('mouseup', onUp);
      document.addEventListener('touchmove', onMove);
      document.addEventListener('touchend', onUp);
    },
    // 触摸处理: touchstart,touchmove,touchend
    tuozhuai(e) {
      const pageX = e.pageX || e.targetTouches[0].pageX;
      const pageY = e.pageY || e.targetTouches[0].pageY;
      // 获取点击时放大镜框坐标和鼠标位置坐标
      const box = document.getElementById('magnifierId');
      const magnifierleft = box.offsetLeft;
      const magnifiertop = box.offsetTop;
      const onMove = (event) => {
        this.doMouseMove(event, magnifierleft, magnifiertop, pageX, pageY);
      };
      const onUp = () => {
        document.removeEventListener('mousemove', onMove);
        document.removeEventListener('mouseup', onUp);
        document.removeEventListener('touchmove', onMove);
        document.removeEventListener('touchend', onUp);
      };
      document.addEventListener('mousemove', onMove);
      document.addEventListener('mouseup', onUp);
      document.addEventListener('touchmove', onMove);
      document.addEventListener('touchend', onUp);
    },
    doMouseMove(event, magnifierleft, magnifiertop, cpagex, cpagey) {
      this.magnifier.bind(
        event,
        (magnifierDiv, menuDiv) => {
          const px = event.pageX || event.targetTouches[0].pageX;
          const py = event.pageY || event.targetTouches[0].pageY;
          magnifierDiv.style.top = `${py - cpagey + magnifiertop}px`;
          magnifierDiv.style.left = `${px - cpagex + magnifierleft}px`;
          menuDiv.style.top = `${py - cpagey + magnifiertop + this.height + 6}px`;
          menuDiv.style.left = `${px - cpagex + magnifierleft + this.width - 60}px`;
        },
        magnifierleft,
        magnifiertop,
        cpagex,
        cpagey,
      );
    },
    doMousewheel(event) {
      if (event && event.preventDefault) {
        event.preventDefault();
      }
      const delta = Math.max(-1, Math.min(1, event.wheelDelta || -event.detail));
      if (delta > 0) {
        this.ratio += 0.5;
      } else {
        this.ratio -= 0.5;
      }
      if (this.ratio < 2) {
        this.ratio = 2;
      }
      this.magnifier.setRatio(this.ratio);
      return false;
    },
  },
};
</script>
<style scoped></style>
